package com.example.recyclerimageload.adapter_flipper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.recyclerimageload.R;

import java.util.List;

public class FlipperAdapter extends BaseAdapter {
    private final String TAG = "FlipperAdapter";
    private final List<String> mDatas;
    private final Context mContext;

    public FlipperAdapter(Context context, List<String> datas){
        this.mContext = context;
        this.mDatas = datas;
    }

    @Override
    public int getCount() {
        return mDatas==null?0:mDatas.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @SuppressLint("CheckResult")
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ImageView imageView = new ImageView(mContext);
        SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                Log.d(TAG, "onResourceReady: ");
                imageView.setImageDrawable(resource);
            }

            @Override
            public void onStart() {
                super.onStart();
                imageView.setImageResource(R.mipmap.loading);
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                Log.d(TAG, "onLoadFailed: ");
            }
        };
        RequestOptions options = new RequestOptions();
        options.diskCacheStrategy(DiskCacheStrategy.ALL);
        options.error(R.mipmap.ic_launcher);
        options.placeholder(R.mipmap.loading);

        Glide.with(mContext).load(mDatas.get(i)).apply(options).into(simpleTarget);

//        imageView.setImageResource(mDatas[i]);

        // 设置ImageView的缩放类型
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        // 为imageView设置布局参数
        imageView.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        return imageView;
    }
}
